package t327.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import t327.pojo.Role;
import t327.pojo.font.AuthCodeFront;
import t327.pojo.font.UserRoleMenuFront;
import t327.service.iter.ILoginService;
import t327.util.IpUtil;
import t327.util.MD5Utils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/login")
public class adminLoginController {

    @Autowired
    private ILoginService loginService;
    private String rolephone;


    @RequestMapping("userLogin")
    public HashMap<String,Object> roleLogin(@RequestBody Role role, HttpServletRequest request) {
        System.out.println("-=-=-=-=-=");
        System.out.println(role);
        System.out.println("-=-=-=-=-=");
        HashMap<String, Object> map = new HashMap<>();
//user做验证

/*        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential("AKIDfJ7mKrP4mPUN4aJ4rV2Ngt3A62sdLVvG", "I1hYM0PaYSI0Wq0yjP1SmxAE5wjN9udK");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("captcha.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setCaptchaType(role.getCaptchaType());
            req.setTicket(role.getTicket());
            String ipAddress = IpUtil.getIpAddress(request);
            req.setUserIp(ipAddress);
            req.setRandstr(role.getRandstr());
            req.setCaptchaAppId(role.getCaptchaAppId());
            req.setAppSecretKey("TusJkBFEa9T16PQn1DNAkbmKC");
            // 返回的resp是一个DescribeCaptchaResultResponse的实例，与请求对象对应
            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            Long captchaCode = resp.getCaptchaCode();
            if(captchaCode!=1L){
                map.put("msg",resp.getCaptchaMsg());
                map.put("code",202);
                return map;
            }
            // 输出json格式的字符串回包
            System.out.println(DescribeCaptchaResultResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }*/




        String rolePassword = role.getRolePassword();
        String rolePhone = role.getRolePhone();
        Role userFind = loginService.userLogin(rolePhone, rolePassword);
        if (userFind!=null) {
            HttpSession session = executeApplication(request, rolePhone);
            //根据roleId查询角色相关的菜单
            // UserRoleMenuFront userRoleMenuFront=  loginService.queryUserRoleMenuFrontByUserId(userFind.getId());
            //String userRoleMenuFrontJsonStr= JSON.toJSONString(userRoleMenuFront);
            UserRoleMenuFront userRoleMenuFront=loginService.queryByRoleId(userFind.getRoleId());
            String userRoleMenuFrontJsonStr= JSON.toJSONString(userRoleMenuFront);
            Role role1 = new Role();
            role1.setRolePhone(userFind.getRolePhone());
            role1.setRoleName(userFind.getRoleName());
            role1.setRoleId(userFind.getRoleId());
            session.setAttribute("role1",role1);
            map.put("msg","登录成功");
            map.put("code",200);
            session.setAttribute("userRoleMenuFront",userRoleMenuFrontJsonStr);
        } else {
            map.put("msg","用户名或者密码错误");
            map.put("code",203);
        }
        return map;
    } /*else if (role==4) {
            Role role = loginService.stuLogin(phone, password);
            if (stuInfo!=null) {
                HttpSession session = executeApplication(request, phone);
                StuRoleMenuFront stuRoleMenuFront=  loginService.queryStuRoleMenuFrontByStuId(stuInfo.getId());
                String stuRoleMenuFrontJsonStr= JSON.toJSONString(stuRoleMenuFront);
                StuInfo stuInfo1 = new StuInfo();
                stuInfo1.setStuBirthday(stuInfo.getStuBirthday());
                stuInfo1.setStuPhone(stuInfo.getStuPhone());
                stuInfo1.setStuName(stuInfo.getStuName());
                stuInfo1.setId(stuInfo.getId());
                session.setAttribute("stuInfo",stuInfo1);
                map.put("msg","登录成功");
                map.put("code",200);
                session.setAttribute("stuRoleMenuFront",stuRoleMenuFrontJsonStr);
            } else {
                map.put("msg","用户名或者密码错误");
                map.put("code",203);
            }
        }else {
            map.put("msg","未知角色");
            map.put("code",203);
        }*/

    /* return map;*/


    private HttpSession executeApplication(HttpServletRequest request, String phone) {
        WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext1 = currentWebApplicationContext.getServletContext();
        HttpSession session = request.getSession();
        String id = session.getId();
        Object attribute = servletContext1.getAttribute(phone);
        servletContext1.setAttribute(id, phone);
        servletContext1.setAttribute(phone, id);
        return session;
    }

    @RequestMapping("sendVerify")
    @ResponseBody
    public Map<String, String> sendVerify(String rolePhone, HttpServletRequest request){
        Map<String,String> map = new HashMap<String,String>();
        String apiUrl="https://sms_developer.zhenzikj.com";
        String appId="113104";//在控制台的 我的应用
        String appSecret="NjFkMDMxOWYtNWJhYi00NDEzLThiNzMtMTc3YjFhNjFiNTE4";//在控制台的 我的应用
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", rolePhone);//你要发送的手机号
        params.put("templateId", "11588");//短信模板里的
        String[] templateParams = new String[2];//模板
        int i = new Random().nextInt(9999 - 1000 + 1);
        int sjs=i+1000;
        templateParams[0] = ""+sjs;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        HttpSession session = request.getSession();
        session.setAttribute("phone",rolePhone);
        session.setAttribute("authCode",templateParams[0]);
        String result = null;
        try {
            result = client.send(params);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message","发送失败");
            return map;
        }
        AuthCodeFront authCodeFront = JSONObject.parseObject(result,AuthCodeFront.class);
        map.put("message",authCodeFront.getData());
        return map;
    }

    @RequestMapping("changPwd")
    @ResponseBody
    public Map<String,String> changPwd(String rolePhone,String verify,HttpServletRequest request){
        //判断手机号是否存在
        Role role = loginService.queryByPhone(rolePhone);
        Map<String,String> map = new HashMap<String,String>();
        if (role==null){
            map.put("message","222");
            return map;
        }
        HttpSession session = request.getSession();
        //判断是否是同一个手机号发送的验证码
        String phone1 = (String)session.getAttribute("phone");
        if (!phone1.equals(rolePhone)){
            map.put("message","555");
            return map;
        }

        //判断验证码是否正确
        String authCode = (String)session.getAttribute("authCode");
        if (authCode ==null||authCode.equals("")){
            map.put("message","444");
            return map;
        }
        System.out.println("------------");
        System.out.println(authCode);
        System.out.println("------------");
        if (!authCode.equals(verify)){
            map.put("message","333");
            return map;
        }
        map.put("message","111");
        return map;
    }

    @RequestMapping("queryPhoneAmendPwd")
    @ResponseBody
    public Map<String,String> queryPhoneAmendPwd(String rolePhone,String rolePassword){
        Map<String,String> map = new HashMap<String,String>();
        String passwordMD5 = MD5Utils.getSaltMD5(rolePassword);
        Integer integer = loginService.updatePassword(rolePhone, passwordMD5);
        if (integer>0){
            map.put("message","修改成功");
            return map;
        }
        map.put("message","修改失败");
        return map;
    }


}
